package com.itheima.advice;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.itheima.mapper.LogMapper;
import com.itheima.pojo.Log;
import com.itheima.service.LogService;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.http.HttpRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

//
@Aspect
@Component
@Slf4j
public class RecordLogAspect {
    @Autowired
    private LogService logService;
//    @Around("execution(* com.itheima.service.impl.*.*(..))")
    @Around("@annotation(com.itheima.advice.RecordLogAnno)")
    public Object RecordTime(ProceedingJoinPoint pjp) throws Throwable {

        long begin = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end - begin;
        String className = pjp.getTarget().getClass().getName();
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        String methodName = methodSignature.getMethod().getName();
        Object[] args = pjp.getArgs();
        log.info(className + "中的" + methodName + "方法,耗时:" + costTime + "ms");
        Log log = new Log();
        log.setOperateEmpId(getId());
        log.setOperateTime(LocalDateTime.now());
        log.setClassName(className);
        log.setMethodName(methodName);
        if(args !=null && args.length>0){
            log.setMethodParams(JSONUtil.toJsonStr(args));
        }
        if(result !=null){
            log.setReturnValue(JSONUtil.toJsonStr(result));
        }
        log.setCostTime(costTime);
        logService.save(log);
        return result;
    }
    public Integer getId(){
        return  CurrentHolder.getUserId();
    }
}
